package com.liuceng.mps.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 随机数生成
 * 
 * @author ryenlea
 * 
 */
public class IdUtils  {
  private IdUtils() {}

  private static SimpleDateFormat sdf = new SimpleDateFormat();

  private static final Sequence sequence = Sequence.getSequence();

  public static String flowid() {
    sdf.applyPattern("yyMMddHHmmss");
    String timetip = sdf.format(new Date());
    return timetip + String.valueOf(sequence.getNextSeq()) + randomNumber(5);
  }
  
  public static String flowid(Date date) {
	    sdf.applyPattern("yyMMddHHmmss");
	    String timetip = sdf.format(date);
	    return timetip + String.valueOf(sequence.getNextSeq()) + randomNumber(5);
	  }
  

  /**
   * 生成lenc长度的随机字符串
   * 
   * @param len
   * @return
   */
  public static final String PROTOTYPE =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  public static String randomString(int len) {
    char[] c = PROTOTYPE.toCharArray();
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < len; i++) {
      sb.append(c[random.nextInt(c.length)]);
    }
    return sb.toString();
  }

  public static final String PROTOTYPE_NUM = "0123456789";

  public static String randomNumber(int len) {
    char[] c = PROTOTYPE_NUM.toCharArray();
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < len; i++) {
      sb.append(c[random.nextInt(c.length)]);
    }
    return sb.toString();
  }

 /* public static void main(String[] args) {
    System.out.println("uuid: " + IdUtils.uuid());
    System.out.println("uuid2:" + IdUtils.uuid2());
    System.out.println("flowid: " + IdUtils.flowid());
    System.out.println("random:" + IdUtils.randomLong());
    System.out.println("random10:" + IdUtils.randomString(10));
  }*/
}


class Sequence {
  private static int key = 1000;
  private static Sequence sequence = null;

  private Sequence() {}

  public static synchronized Sequence getSequence() {
    if (sequence == null) {
      sequence = new Sequence();
    }
    return sequence;
  }

  public int getNextSeq() {
    synchronized (sequence) {
      if (key == 9999) {
        key = 1000;
        return key++;
      } else {
        return key++;
      }
    }
  }
}
